package com.ithinks.flow.common.utils.protocol.socket.aio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * @Description
 * @ClassName AioServerHandler
 * @Author MR.LI
 * @date 2020.12.07 18:13
 */
public class AioServerHandler implements Runnable{

    public CountDownLatch latch;

    //进行异常通信得通道
    public AsynchronousServerSocketChannel channel;

    public AioServerHandler(int port){
        try {
            //创建通道
            channel = AsynchronousServerSocketChannel.open();
            //绑定端口
            channel.bind(new InetSocketAddress(port));
            System.out.println("server is start ,port:{}"+port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);
        channel.accept(this,new AioAcceptHandler());
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
